package com.sh.caryr.erp.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sh.caryr.erp.entity.product.CombDetail;
import com.sh.caryr.erp.entity.product.CombNum;
import com.sh.caryr.erp.entity.product.Product;
import com.sh.caryr.erp.entity.product.ProductSpec;
import com.sh.caryr.erp.entity.stock.Sku;
import com.sh.caryr.erp.entity.enums.ProductTypeEnum;
import com.sh.caryr.erp.exception.ResultCode;
import com.sh.caryr.erp.exception.RestServiceException;
import com.sh.caryr.erp.mapper.ProductMapper;
import com.sh.caryr.erp.service.*;
import com.sh.caryr.erp.util.MyBatisUtil;
import com.sh.caryr.erp.util.UtilityTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author milkeeper
 * @since 2017-11-22
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ISkuService skuService;
    @Autowired
    private ICombDetailService combDetailService;
    @Autowired
    private ICombNumService combNumService;
    @Autowired
    private IProductSpecService productSpecService;

    @Transactional
    @Override
    public void insertProduct(Product product) {
        //==============Insert product
        if (!this.insert(product)) {
            new RestServiceException(ResultCode.CREATE_FAILED);
        }
        //==============Insert product specification list
        updateDefaultValue(product);
        List<ProductSpec> productSpecList = product.getProductSpecList();
        if (!productSpecService.insertProductSpecList(productSpecList)) {
            new RestServiceException(ResultCode.CREATE_FAILED);
        }
    }

    @Transactional
    @Override
    public void updateProduct(Product product) {
        if (!this.updateById(product)) {
            throw new RestServiceException(ResultCode.UPDATE_FAILED);
        }
        //==============Update product specification list
        updateDefaultValue(product);
        Wrapper wrapper = new EntityWrapper<Sku>().eq("productId", product.getId());
        List<ProductSpec> oldProductSpecList = productSpecService.findProductSpecsDynamic(wrapper);
        List<ProductSpec> productSpecList = product.getProductSpecList();
        try{
            List<Long> ids = MyBatisUtil.getDeleteEntityIds(ProductSpec.class,oldProductSpecList,productSpecList);
            if (!productSpecService.updateProductSpecList(productSpecList)) {
                new RestServiceException(ResultCode.CREATE_FAILED);
            }
            if(!ids.isEmpty()){
                productSpecService.deleteBatchIds(ids);
            }
        } catch (Exception e) {
            e.printStackTrace();
            new RestServiceException(ResultCode.CREATE_FAILED);
        }
    }

    @Override
    public void getProductDetail(Product product) {
        Wrapper wrapper = new EntityWrapper<Sku>().eq("productId", product.getId());
        wrapper.eq("isActive", "1");
        product.setProductSpecList(productSpecService.findProductSpecsDynamic(wrapper));
    }

    @Override
    public List<Product> findProductsDynamic(Integer current, Integer size, String queryField, String queryValue, Boolean isAccurate, String orderBy) {
        Wrapper wrapper = new EntityWrapper<>();
        if (isAccurate != null) {
            if (isAccurate) {
                wrapper.eq(queryField, queryValue);
            } else {
                wrapper.like(queryField, queryValue);
            }
        }
        return this.findProductsDynamic(new Page<Product>(current, size), wrapper.orderBy(orderBy));
    }

    @Override
    public List<Product> findProductsDynamic(Integer current, Integer size, Wrapper wrapper, String orderBy) {
        return this.findProductsDynamic(new Page<Product>(current, size), wrapper.orderBy(orderBy));
    }

    private List<Product> findProductsDynamic(Page<Product> page, Wrapper<Product> wrapper) {
        Page<Product> productPage = this.selectPage(page, wrapper);
        for (Product product : productPage.getRecords()) {
            this.getProductDetail(product);
        }
        return productPage.getRecords();
    }

    @Override
    @Transactional
    public void deleteProductById(Long id) {
        Product product = this.selectById(id);
        if (ProductTypeEnum.NORMAL == product.getType()) {
            //普通商品
            skuService.delete(new EntityWrapper<Sku>().eq("productId", product.getId()));

        } else {
            //套件商品
            List<CombDetail> combDetailList = combDetailService.selectList(new EntityWrapper<CombDetail>().eq("productId", product.getId()));

            for (CombDetail combDetail : combDetailList) {
                combNumService.delete(new EntityWrapper<CombNum>().eq("combDetailId", combDetail.getId()));
            }

            combDetailService.delete(new EntityWrapper<CombDetail>().eq("productId", product.getId()));
        }
        this.deleteById(id);
    }

    private void updateDefaultValue(Product product) {
        List<ProductSpec> productSpecList = product.getProductSpecList();
        for (ProductSpec spec : productSpecList) {
            spec.setCoco(product.getCoco());
            spec.setType(product.getType());
            spec.setShopId(product.getShopId());
            spec.setProductId(product.getId());
            spec.setProductName(product.getName());
            spec.setIsActive(product.getIsActive());
            Sku sku = spec.getSku();
            if (sku != null) {
                sku.setCoco(spec.getCoco());
                sku.setProductId(spec.getProductId());
            }
        }
    }
}
